<template>
  <ElButton
    v-if="isVisible && (footer || toolbar.footer)"
    :disabled="disabled || loading"
    :circle="circle"
    :loading="loadable ? loading : false"
    :type="type"
    @click="onClick">
    <template v-if="!circle">
      <slot>{{ label }}</slot>
    </template>
  </ElButton>
  <ElButton
    v-else-if="isVisible"
    :disabled="disabled || loading"
    :icon="icon"
    size="mini"
    :circle="circle"
    :loading="loadable ? loading : false"
    :type="type"
    @click="onClick">
    <template v-if="!circle">
      <slot>{{ label }}</slot>
    </template>
  </ElButton>
</template>

<script>
  import { isFunction } from '@web-utils/core'
  import { hasAuthority } from '@/util/auth'

  export default {
    name: 'ToolbarButton',
    inject: {
      toolbar: {
        default: ''
      }
    },
    inheritAttrs: false,
    props: {
      label: String,
      icon: String,
      type: String,
      loadable: Boolean,
      disabled: Boolean,
      footer: Boolean,
      circle: Boolean,
      privilege: String
    },
    data() {
      return {
        loading: false
      }
    },
    computed: {
      isVisible() {
        if (!this.privilege) {
          return true
        } else {
          return hasAuthority(this.privilege)
        }
      }
    },
    methods: {
      async onClick(e) {
        this.loading = true
        const { click } = this.$listeners
        if (isFunction(click)) {
          try {
            await click(e)
          } catch (e) {
            // 不需要处理错误
          }
        }
        this.loading = false
      }
    }
  }
</script>
